package com.hahaliu.hahaliu.controller.user;

import com.hahaliu.hahaliu.common.context.CurrentUser;
import com.hahaliu.hahaliu.common.exception.BaseException;
import com.hahaliu.hahaliu.common.result.Result;
import com.hahaliu.hahaliu.common.utils.RedisUtil;
import com.hahaliu.hahaliu.service.message.ChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/user/chat")
@Api(tags = "用户端聊天相关接口")
@Slf4j
public class ChatController {
	@Autowired
	private ChatService chatService;

	@Autowired
	private CurrentUser currentUser;

	@Autowired
	private RedisUtil redisUtil;

	@GetMapping("/create/{uid}")
	@ApiOperation("新建一个聊天")
	public Result<Map<String, Object>> createChat(@PathVariable("uid") Integer uid) {
		log.info("ChatController createChat uid:{}", uid);
		Map<String, Object> result = chatService.createChat(uid, currentUser.getUserId());
		if (Objects.equals(result.get("msg").toString(), "新创建")) {
			return Result.success(result);// 返回新创建的聊天
		} else if (Objects.equals(result.get("msg").toString(), "未知用户")) {
			throw new BaseException("未知用户~");
		}
		return Result.success(result);
	}

	@GetMapping("/recent-list")
	@ApiOperation("获取用户最近的聊天列表")
	public Result getRecentList(@RequestParam("offset") Long offset) {
		log.info("ChatController getRecentList offset:{}", offset);
		Integer uid = currentUser.getUserId();
		Map<String, Object> map = new HashMap<>();
		map.put("list", chatService.getChatListWithData(uid, offset));
		// 检查是否还有更多
		if (offset + 10 < redisUtil.zCard("chat_zset:" + uid)) {
			map.put("more", true);
		} else {
			map.put("more", false);
		}
		return Result.success(map);
	}

	@GetMapping("/delete/{uid}")
	@ApiOperation("删除聊天")
	public Result deleteChat(@PathVariable("uid") Integer uid) {
		log.info("ChatController deleteChat uid:{}", uid);
		chatService.delChat(uid, currentUser.getUserId());
		return Result.success();
	}

	@GetMapping("/online")
	@ApiOperation("更新在线状态")
	public Result updateWhisperOnline(@RequestParam("from") Integer from) {
		log.info("ChatController updateWhisperOnline from:{}", from);
		Integer uid = currentUser.getUserId();
		chatService.updateWhisperOnline(from, uid);
		return Result.success();
	}

	@GetMapping("/outline")
	@ApiOperation("更新为离开状态")
	public Result updateWhisperOutline(@RequestParam("from") Integer from, @RequestParam("to") Integer to) {
		log.info("ChatController updateWhisperOutline from:{}", from);
		log.info("ChatController updateWhisperOutline to:{}", to);
		chatService.updateWhisperOutline(from, to);
		return Result.success();
	}

}
